package cn.bigfire.wzdj.util;

import cn.bigfire.wzdj.pojo.httpVo.AuthRes;
import cn.bigfire.wzdj.pojo.httpVo.UserInfo;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import io.netty.util.internal.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.requests.Requests;

import java.util.HashMap;
import java.util.TreeMap;

/**
 * 获取方法
 * 关注如下两个数据包,抓第一个数据包获取 accessToken
 * https://sdkapi.hnys68.cn/api/sdk/v2/accounts/action/registerlogin/openuser-mp?appId=2074&pid=2074010&clientType=5&encryptflag=0&uuid=wx-ol9sW7RiscrRqWOQ1wPrQSP0NKEM&timestamp=1729997157&version=v2&subUserType=1051&sign=2ca6e95315a3f2328ce67ba99d2a61091b8da48cd4d0388fd33c75ce07daaa6c
 * 发第二个数据包，进行登录获取 登录token
 * https://wzdj.hnys68.cn:20002/auth?token=【accessToken】&channel=bc_wechat&subChannel=&openid=366977426&pid=2074010&gid=2074&uuid=wx-ol9sW7RiscrRqWOQ1wPrQSP0NKEM
 *
 */
@Slf4j
public class AuthUtil {

    //大火
//    public static UserInfo authDahuo() {
//        String openid = "366977426";
//        String uuid = "wx-ol9sW7RiscrRqWOQ1wPrQSP0NKEM";
//        String accessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiMzY2OTc3NDI2IiwiVVVJRCI6Ind4LW9sOXNXN1Jpc2NyUnFXT1Exd1ByUVNQME5LRU0iLCJHYW1lSWQiOiIyMDc0IiwiVXNlcklkIjoiMzY2OTc3NDI2IiwiVXNlck5hbWUiOiJiY2E1MzA2MDc1IiwiSXNQYXNzV29yZCI6InRydWUiLCJJc0JpbmRNb2JpbGUiOiJmYWxzZSIsIlJlYWxOYW1lU3RhdHVzIjoiMSIsIk5vbmVLaWQiOiIxIiwiSXNWaXNpdG9yIjoiZmFsc2UiLCJJc05ld1VzZXIiOiJmYWxzZSIsIlBpZCI6IjIwNzQwMTAiLCJDbGllbnRUeXBlIjoiNSIsIlB3ZGNvZGUiOiItMTI1NjYyMTU4OCIsIklkQ2FyZExvY2tlZFN0YXR1cyI6IjAiLCJJZENhcmRMb2NrZWRNc2ciOiIiLCJPcGVuSWQiOiJvbDlzVzdSaXNjclJxV09RMXdQclFTUDBOS0VNIiwiSGFzTmV3VXNlciI6IjAiLCJBZGluZm8iOiIiLCJSc2lkIjoiIiwiQWRSZXNldEZsYWciOiIwIiwiTGFzdExvZ2luIjoiMTczMTQyMDkxNCIsIm5iZiI6MTczMTQyMTQ2MiwiZXhwIjoxNzMxNjgwNjYyLCJpc3MiOiJxMS5jb20iLCJhdWQiOiJFdmVyeW9uZSJ9.8KXXDU-wDExDOrDId5zU80sDs-9PJVsZDgi0N8-z76I";
//        //accessToken 获取时间 2024-11-09 22:04   token 超过三天就失效了。
//        return auth(openid, uuid, accessToken);
//        //refreshToken目前不太清楚怎么用。应该是可以续费 accessToken 的，但是目前不会用。
//    }

    //小胖子
//    public static UserInfo authXiaoPang() {
//        String userId = "380914732";
//        String uuid = "wx-ol9sW7VjpUsetDMb4mrstkAWQNv4";
//        String accessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiMzgwOTE0NzMyIiwiVVVJRCI6Ind4LW9sOXNXN1ZqcFVzZXRETWI0bXJzdGtBV1FOdjQiLCJHYW1lSWQiOiIyMDc0IiwiVXNlcklkIjoiMzgwOTE0NzMyIiwiVXNlck5hbWUiOiJiY2EyMjIxNTYzIiwiSXNQYXNzV29yZCI6InRydWUiLCJJc0JpbmRNb2JpbGUiOiJmYWxzZSIsIlJlYWxOYW1lU3RhdHVzIjoiMSIsIk5vbmVLaWQiOiIxIiwiSXNWaXNpdG9yIjoiZmFsc2UiLCJJc05ld1VzZXIiOiJmYWxzZSIsIlBpZCI6IjIwNzQwMTAiLCJDbGllbnRUeXBlIjoiNSIsIlB3ZGNvZGUiOiItMTc0OTc3OTUwOCIsIklkQ2FyZExvY2tlZFN0YXR1cyI6IjAiLCJJZENhcmRMb2NrZWRNc2ciOiIiLCJPcGVuSWQiOiJvbDlzVzdWanBVc2V0RE1iNG1yc3RrQVdRTnY0IiwiSGFzTmV3VXNlciI6IjAiLCJBZGluZm8iOiIiLCJSc2lkIjoiIiwiQWRSZXNldEZsYWciOiIwIiwiTGFzdExvZ2luIjoiMTczMTQxOTYyOCIsIm5iZiI6MTczMTQyMDY0MywiZXhwIjoxNzMxNjc5ODQzLCJpc3MiOiJxMS5jb20iLCJhdWQiOiJFdmVyeW9uZSJ9.bkKrDrgwq--xZYijkD5ma06_M671-MWrMwfTWCodNyY";
//        return auth(userId, uuid, accessToken);
//    }

    //菲菲
//    public static UserInfo authFeiFei() {
//        String userId = "376187134";
//        String uuid = "wx-ol9sW7YrpRzFQHUaOjRTVUCLW7iE";
//        String accessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiMzc2MTg3MTM0IiwiVVVJRCI6Ind4LW9sOXNXN1lycFJ6RlFIVWFPalJUVlVDTFc3aUUiLCJHYW1lSWQiOiIyMDc0IiwiVXNlcklkIjoiMzc2MTg3MTM0IiwiVXNlck5hbWUiOiJiY2E2NTQxODk5IiwiSXNQYXNzV29yZCI6InRydWUiLCJJc0JpbmRNb2JpbGUiOiJmYWxzZSIsIlJlYWxOYW1lU3RhdHVzIjoiMSIsIk5vbmVLaWQiOiIxIiwiSXNWaXNpdG9yIjoiZmFsc2UiLCJJc05ld1VzZXIiOiJmYWxzZSIsIlBpZCI6IjIwNzQwMTQiLCJDbGllbnRUeXBlIjoiNSIsIlB3ZGNvZGUiOiItOTk3MDIyNzUxIiwiSWRDYXJkTG9ja2VkU3RhdHVzIjoiMCIsIklkQ2FyZExvY2tlZE1zZyI6IiIsIk9wZW5JZCI6Im9sOXNXN1lycFJ6RlFIVWFPalJUVlVDTFc3aUUiLCJIYXNOZXdVc2VyIjoiMCIsIkFkaW5mbyI6IntcInJhZGlkXCI6XCJxcV9rbV9zY2ZmX3d6ZGppb3M5NTIyXCIsXCJ3eF9haWRcIjpcIjIxMjU2ODIyNzA0XCIsXCJ3eF90cmFjZWlkXCI6XCJ3eDBlamg1c2FnZWdmbXhjMDFcIixcIndlaXhpbmFkaW5mb1wiOlwiMjEyNTY4MjI3MDQud3gwZWpoNXNhZ2VnZm14YzAxLjAuMFwiLFwicGlkXCI6XCIyMDc0MDE0XCIsXCJnZHRfdmlkXCI6XCJ3eDBlamg1c2FnZWdmbXhjMDFcIn0iLCJSc2lkIjoiMjEyNTY4MjI3MDQiLCJBZFJlc2V0RmxhZyI6IjAiLCJMYXN0TG9naW4iOiIxNzMxMzY1OTAyIiwibmJmIjoxNzMxNDUxMjY5LCJleHAiOjE3MzE3MTA0NjksImlzcyI6InExLmNvbSIsImF1ZCI6IkV2ZXJ5b25lIn0.kJBTJep9fkB_k8lY3G92X0DnOoJ2nDs2_TSyDz7NvVo";
//        return auth(userId, uuid, accessToken);
//    }

    //其他
//    public static UserInfo authOther() {
//        String userId = "366977426";
//        String uuid = "wx-ol9sW7RiscrRqWOQ1wPrQSP0NKEM";
//        String accessToken = "";
//        return auth(userId, uuid, accessToken);
//    }


    private static final String authApiTlp = "https://wzdj.hnys68.cn:20002/auth?token=%s&channel=bc_wechat&subChannel=&openid=%s&pid=2074010&gid=2074&uuid=%s";

    public static HashMap<String, String> headers() {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Host", "wzdj.hnys68.cn:20002");
        headers.put("Connection", "keep-alive");
        headers.put("xweb_xhr", "1");
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c11)XWEB/11275");
        headers.put("Accept", "*/*");
        headers.put("Sec-Fetch-Site", "cross-site");
        headers.put("Sec-Fetch-Mode", "cors");
        headers.put("Sec-Fetch-Dest", "empty");
        headers.put("Referer", "https://servicewechat.com/wx71702c33334e92bd/14/page-frame.html");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        return headers;
    }

    public static AuthRes auth(String accessToken,String userId, String openId) {
        try {
            //paramMap
//        String uuid = "wx-ol9sW7RiscrRqWOQ1wPrQSP0NKEM";//用户wx- openId
            TreeMap<String,String> paramMap = new TreeMap<>();
            paramMap.put("token", accessToken);
            paramMap.put("openid", userId);
            paramMap.put("channel", "bc_wechat");//bc_wechat 电脑端微信
            paramMap.put("subChannel", "");
            paramMap.put("pid", "2074010");
            paramMap.put("gid", "2074");
            paramMap.put("uuid", openId);

            String authApi = "https://wzdj.hnys68.cn:20002/auth";
            String readToText = Requests.get(authApi).params(paramMap).headers(headers()).send().readToText();
            log.info("api:{}",authApi);
            log.info("result:{}",readToText);
            if (JSONUtil.isTypeJSONObject(readToText)) {
                AuthRes authRes =  JSON.parseObject(readToText, AuthRes.class);
                if (0 == authRes.getCode()) {
                    return authRes;
                } else if (15 == authRes.getCode()) {//3天有效期的 accessToken 已失效
                    log.error(JSON.toJSONString(authRes));
                }else if (22 == authRes.getCode()) {//服务器维护中（预计开服时间 08:59）
                    log.error(JSON.toJSONString(authRes));
                } else {
                    log.error("没见过的错误,要留一下:{}", JSON.toJSONString(authRes));
                }
            }
        } catch (Exception e) {
            log.error("auth has Exception:{}", ThrowableUtil.stackTraceToString(e));
        }
        return null;
    }

//    private static final String refreshTokenApiTlp = "https://wzdj.hnys68.cn:20002/auth?refreshToken=%s&channel=bc_wechat&subChannel=&openid=%s&pid=2074010&gid=2074&uuid=%s";
    private static final String refreshTokenApiTlp = "https://wzdj.hnys68.cn:20002/auth?refreshToken=%s&channel=bc_wechat&subChannel=&openid=%s&pid=2074010&gid=2074&uuid=%s";
    public static UserInfo refreshToken(String openid, String uuid, String refreshToken) {
        try {
            String authApi = String.format(refreshTokenApiTlp, refreshToken, openid, uuid);
            log.info(authApi);
            HttpRequest httpRequest = HttpUtil.createGet(authApi);
            httpRequest.addHeaders(headers());
            String body = httpRequest.execute().body();
            log.info(body);
            if (JSONUtil.isTypeJSONObject(body)) {
//                JSONObject jsonObject = JSON.parseObject(body);
//                if (jsonObject!=null && 0 == jsonObject.getInteger("code")) {
//                    UserInfo userInfo = jsonObject.getObject("userdInfo", UserInfo.class);
//                    if (userInfo != null) {
//                        userInfo.setOpenid(openid);
//                        userInfo.setUuid(uuid);
//                        return userInfo;
//                    }
//                }
            }
        } catch (Exception e) {
            System.err.printf("auth has err:" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
